﻿#include <stdio.h>
#include <stdlib.h>
#include <uv.h>

uv_loop_t loop;
int nerror = 0;

void on_change(uv_fs_event_t* handle, const char* filename, int events, int status){
    char path[1024];
    size_t size = 1023;
    // Does not handle error if path is longer than 1023.
    uv_fs_event_getpath(handle, path, &size);
    path[size] = '\0';

    fprintf(stderr, "Change detected in %s: ", path);
    if (events & UV_RENAME)
        fprintf(stderr, "renamed");
    if (events & UV_CHANGE)
        fprintf(stderr, "changed");

    fprintf(stderr, " %s\n", filename ? filename : "");
}

int main(int argc, char* argv[]) {
    fprintf(stdout, "fs onchange demo.\n");
    if( argc < 2 ){
        fprintf(stdout,"usage: %s <file or directory> ...\n", argv[0]);
        return 1;
    }
    uv_loop_init(&loop);

    for(int i=1;i<argc;i++){
        fprintf(stdout, "Add watch on: %s\n", argv[i]);
        uv_fs_event_t* fs_req = new uv_fs_event_t;
        uv_fs_event_init(&loop, fs_req);
        uv_fs_event_start(fs_req, on_change, argv[i], UV_FS_EVENT_RECURSIVE);
    }

    nerror = uv_run(&loop, UV_RUN_DEFAULT);
    return nerror;
}
